import React, { useState, useEffect, useCallback } from 'react';
import { Table, Button, message, Card, Space, Tag, Input } from 'antd';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import { LoadingOutlined, SearchOutlined } from '@ant-design/icons';
import axios from 'axios';

interface Club {
  id: number;
  name: string;
  description: string;
  type: string;
  president: string;
  created_at: string;
  status: string | null;
}

interface ApiResponse<T> {
  success: boolean;
  data: T;
  message?: string;
}

const JoinClub: React.FC = () => {
  const [clubs, setClubs] = useState<Club[]>([]);
  const [filteredClubs, setFilteredClubs] = useState<Club[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [searchText, setSearchText] = useState<string>('');
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  const fetchClubs = useCallback(async () => {
    setLoading(true);
    try {
      const userInfo = localStorage.getItem('userInfo');
      if (!userInfo) {
        message.error('请先登录');
        return;
      }

      const studentInfo = JSON.parse(userInfo);
      const response = await axios.get<ApiResponse<Club[]>>('http://localhost:5000/api/allClubs');
      if (response.data.success) {
        const statusResponse = await axios.get(`http://localhost:5000/api/studentClubs/student/${studentInfo.id}`);
        const statusMap = new Map(statusResponse.data.map((item: any) => [item.club_id, item.status]));
        
        const clubsWithStatus = response.data.data.map(club => ({
          ...club,
          status: statusMap.get(club.id) || null
        })) as Club[];

        setClubs(clubsWithStatus);
        setFilteredClubs(clubsWithStatus);
        setPagination(prev => ({
          ...prev,
          total: response.data.data.length,
        }));
      } else {
        message.error('获取社团列表失败');
      }
    } catch (error) {
      console.error('获取社团列表失败:', error);
      message.error('获取社团列表失败');
    } finally {
      setLoading(false);
    }
  }, []);

  const handleSearch = (value: string) => {
    setSearchText(value);
    if (value.trim() === '') {
      setFilteredClubs(clubs);
    } else {
      const filtered = clubs.filter(club => 
        club.type.toLowerCase().includes(value.toLowerCase())
      );
      setFilteredClubs(filtered);
    }
  };

  const handleJoinClub = useCallback(async (clubId: number) => {
    try {
      const userInfo = localStorage.getItem('userInfo');
      if (!userInfo) {
        message.error('请先登录');
        return;
      }

      const studentInfo = JSON.parse(userInfo);
      const response = await axios.post<ApiResponse<null>>('http://localhost:5000/api/SjoinClub', {
        student_id: studentInfo.id,
        club_id: clubId
      });
      
      if (response.data.success) {
        message.success('申请加入社团成功');
        // 立即更新本地状态
        setClubs(prevClubs => 
          prevClubs.map(club => 
            club.id === clubId ? { ...club, status: 'pending' } : club
          )
        );
        // 然后重新获取完整数据
        await fetchClubs();
      } else {
        message.error(response.data.message || '申请失败');
      }
    } catch (error) {
      console.error('申请加入社团失败:', error);
      message.error('申请加入社团失败');
    }
  }, [fetchClubs]);

  const getStatusTag = (status: string | null) => {
    if (!status) return null;
    
    const statusConfig = {
      pending: { color: 'orange', text: '待受理' },
      approved: { color: 'green', text: '已通过' },
      rejected: { color: 'red', text: '已拒绝' }
    };

    const config = statusConfig[status as keyof typeof statusConfig];
    return config ? <Tag color={config.color}>{config.text}</Tag> : null;
  };

  const handleTableChange = useCallback((newPagination: TablePaginationConfig) => {
    setPagination(newPagination);
  }, []);

  const columns: ColumnsType<Club> = [
    {
      title: '社团ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      align: 'center',
      sorter: (a, b) => a.id - b.id,
    },
    {
      title: '社团名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      ellipsis: true,
    },
    {
      title: '社团描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '负责人',
      dataIndex: 'president',
      key: 'president',
      width: 120,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 150,
      render: (date: string) => new Date(date).toLocaleDateString(),
      sorter: (a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime(),
    },
    {
      title: '状态',
      key: 'status',
      width: 100,
      render: (_, record) => getStatusTag(record.status),
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_, record) => (
        <Space size="middle">
          {!record.status ? (
            <Button 
              type="primary" 
              onClick={() => handleJoinClub(record.id)}
            >
              申请加入
            </Button>
          ) : (
            <Button disabled>
              {record.status === 'pending' ? '待受理' : 
               record.status === 'approved' ? '已通过' : '已拒绝'}
            </Button>
          )}
        </Space>
      ),
    },
  ];

  useEffect(() => {
    fetchClubs();
  }, [fetchClubs]);

  return (
    <Card 
      title="社团列表" 
      variant="outlined"
      extra={
        <Space>
          <Input
            placeholder="输入社团类型搜索"
            prefix={<SearchOutlined />}
            value={searchText}
            onChange={(e) => handleSearch(e.target.value)}
            style={{ width: 200 }}
            allowClear
          />
          <Button type="primary" onClick={fetchClubs} loading={loading}>
            刷新
          </Button>
        </Space>
      }
    >
      <Table<Club>
        columns={columns}
        dataSource={filteredClubs}
        rowKey="id"
        loading={{
          spinning: loading,
          indicator: <LoadingOutlined style={{ fontSize: 24 }} spin />,
        }}
        pagination={{
          ...pagination,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: total => `共 ${total} 条`,
        }}
        onChange={handleTableChange}
        bordered
        scroll={{ x: 'max-content' }}
      />
    </Card>
  );
};

export default JoinClub;
